import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_baselib_example/common/config/login_info_manager.dart';
import 'package:flutter_baselib_example/common/net/http_urls.dart';
import 'package:flutter_baselib_example/module/login/model/login_result_bean.dart';
import 'package:flutter_baselib_example/module/userlist/model/user_detail_bean.dart';

///@date:  2021/3/1 11:57
///@author:  lixu
///@description: 登录ViewModel
class LoginViewModel extends BaseCommonViewModel {
  ///登录响应对象
  LoginResultBean? _loginResultBean;

  CancelToken? loginCancelToken;

  LoginResultBean? get loginResultBean => _loginResultBean;

  @override
  String getTag() {
    return 'LoginViewModel';
  }

  ///登录：http请求返回单个对象
  Future<bool> onLogin(BuildContext context, {bool isCancelableDialog = true}) async {
    Map<String, dynamic> map = {
      'account': '15015001500',
      'pass': '123qwe',
      'appType': 'PATIENT',
      'device': 'ANDROID',
      'push': '13065ffa4e22e63efd2',
    };

    loginCancelToken = CancelToken();

    ///TODO http请求方法全部字段功能说明
    Options option = Options();
    option.method = XApi.methodGet;

    await api.request<LoginResultBean>(
      HttpUrls.loginUrl,
      params: map,
      //优先级最高
      method: XApi.methodPost,
      //针对当前请求的配置选项，优先级次高
      option: option,
      cancelToken: loginCancelToken,
      //请求前检测网络连接是否正常，如果连接异常，直接返回错误
      isCheckNetwork: true,
      //显示加载dialog
      isShowLoading: true,
      //加载dialog显示的提示文本
      loadingText: '正在登录...',
      //请求失败时显示toast提示
      isShowFailToast: true,
      //TODO 请求过程中可以关闭加载弹窗（请求过程中关闭dialog时自动取消请求）
      isCancelableDialog: isCancelableDialog,
      onSuccess: (LoginResultBean? bean) {
        _loginResultBean = bean;
        ToastUtils.show('登录成功');
      },
      onError: (HttpErrorBean errorBean) {
        _loginResultBean = null;
        LogUtils.e(getTag(), '登录失败');
      },
      onComplete: () {
        LogUtils.i(getTag(), '登录完成');
      },
    );
    notifyListeners();
    return _loginResultBean?.token != null && _loginResultBean?.user != null;
  }

  ///TODO 此处只是为了演示http获取List对象
  ///获取用户列表
  Future<List<UserDetailBean>?> getUserList(BuildContext context) async {
    if (_loginResultBean == null) {
      ///先登录获取token添加到请求头
      await onLogin(context, isCancelableDialog: false);
    }

    var params = {
      'userId': loginInfo.userBean?.userId,
      'token': loginInfo.token,
    };

    List<UserDetailBean>? userList;
    await api.requestList<UserDetailBean>(
      HttpUrls.userListUrl,
      params: params,
      loadingText: '加载中...',
      isCancelableDialog: false,
      onSuccess: (List<UserDetailBean>? list) {
        userList = list;
        ToastUtils.show('获取用户列表成功，用户数：${list?.length}');
      },
      onError: (HttpErrorBean errorBean) {
        LogUtils.e(getTag(), '获取用户列表失败');
      },
    );

    return userList;
  }

  ///TODO 此处演示最简单的http请求
  Future<void> simplestHttpDemo(BuildContext context) async {
    if (_loginResultBean == null) {
      ///先登录获取token添加到请求头
      await onLogin(context, isCancelableDialog: false);
    }

    var params = {
      'userId': loginInfo.userBean?.userId,
      'token': loginInfo.token,
    };

    ///下面请求包含的功能：
    ///1、自动显示隐藏加载dialog，请求过程中dialog不能关闭
    ///2、请求失败自动显示Toast提示错误信息
    ///3、使用post方法请求
    await api.requestList<UserDetailBean>(
      HttpUrls.userListUrl,
      params: params,
      onSuccess: (List<UserDetailBean>? list) {
        ToastUtils.show('获取用户列表成功，用户数：${list?.length}');
      },
    );
  }

  @override
  void dispose() {
    ///页面关闭时，取消http请求
    api.cancel(loginCancelToken);
    super.dispose();
  }
}
